package com.v1.video.activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.v1.video.R;

public class CustomCameraActivity extends Activity implements
		SurfaceHolder.Callback, OnItemSelectedListener, OnClickListener,
		PictureCallback {
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
		
		if(mHolder!=null){
			mHolder.removeCallback(this);
			mHolder=null;
		}
		
		if(mCameraSV!=null){
			mCameraSV=null;
		}
	}

	private static final String TAG = "CustomCamera_GetOrSaveImg";
	private SurfaceView mCameraSV;
	private ImageView mPicIV;
	private Camera mCamera = null;
	private SurfaceHolder mHolder;

	private View mCameraLay;
	private View mPicLay;

	private Button mTakePicBtn;
	private Button mChangeHead;
	private Button mCancelBtn;
	private Button mConfirmBtn;
	
	private Uri uri;

	// private Spinner colorsp;
	// private List<String> colors = new ArrayList<String>();
	// private ArrayAdapter<String> adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customcamera);
		mCameraSV = (SurfaceView) findViewById(R.id.cameraSV);

		this.mCameraLay = findViewById(R.id.cameraLay);
		this.mCameraLay.setVisibility(View.VISIBLE);
		this.mPicLay = findViewById(R.id.picLay);
		this.mTakePicBtn = (Button) findViewById(R.id.TakePicBtn);
		this.mChangeHead = (Button) findViewById(R.id.ChangeHead);
		this.mCancelBtn = (Button) findViewById(R.id.CancelBtn);
		this.mConfirmBtn = (Button) findViewById(R.id.ConfirmBtn);

		this.mTakePicBtn.setOnClickListener(this);
		this.mChangeHead.setOnClickListener(this);
		this.mCancelBtn.setOnClickListener(this);
		this.mConfirmBtn.setOnClickListener(this);

		mCameraSV.setFocusable(false);
		mCameraSV.setFocusableInTouchMode(false);
		mCameraSV.setClickable(false);
		mPicIV = (ImageView) findViewById(R.id.picIV);
		/*
		 * colorsp = (Spinner) findViewById(R.id.colorSp); adapter = new
		 * ArrayAdapter<String>(this,
		 * android.R.layout.simple_spinner_dropdown_item, android.R.id.text1,
		 * colors); colorsp.setAdapter(adapter);
		 * colorsp.setOnItemSelectedListener(this);
		 */
		mHolder = mCameraSV.getHolder();
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mHolder.addCallback(this);
	}

	@SuppressLint("NewApi")
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		int index = 0;
		for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++) {
			CameraInfo cameraInfo = new CameraInfo();
			Camera.getCameraInfo(camIdx, cameraInfo);
			if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
				// 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
				index = camIdx;
			}
		}

		try {
			mCamera = Camera.open(0);
		} catch (RuntimeException ex) {
			Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
		}

		if (mCamera == null) {
			mCamera = Camera.open();
		}

		// Camera.getNumberOfCameras()
		// 调整照相机镜头方向
		setCameraOrientation();

		// 设置合适的镜头大小
		// setCameraHeadSize();

		// 获取相机支持的颜色
		// getSupportedColorEffects();

		Parameters pm = mCamera.getParameters();
		// 设置闪光灯模式
		pm.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
		// 设置对焦模式
		pm.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);

		mCamera.setParameters(pm);

		try {
			mCamera.setPreviewDisplay(mHolder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mCamera.startPreview();

		// 10秒后自动拍照
		// autoPhoto();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		//mCamera.autoFocus(this);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mCamera.stopPreview();
		mCamera.release();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Parameters pm = mCamera.getParameters();
		// pm.setColorEffect(colors.get(position));
		mCamera.setParameters(pm);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub

	}

	// 捕获照片数据
	@Override
	public void onClick(View v) {
		// takePicture后系统自动停止预览模式，在回调方法中再主动打开预览
		// mCamera.takePicture(null, null, null, this);
		switch (v.getId()) {
		case R.id.TakePicBtn:
			uri=null;
			mCamera.takePicture(null, null, null, this);
			break;
		case R.id.ChangeHead:
			break;
		case R.id.CancelBtn:
			mCamera.startPreview();
			this.mPicLay.setVisibility(View.GONE);
			this.mCameraLay.setVisibility(View.VISIBLE);
			break;
		case R.id.ConfirmBtn:
			if (mCamera != null) {
				mCamera.stopPreview();
				mCamera.release();
				mCamera = null;
			}
			
			if(mHolder!=null){
				mHolder.removeCallback(this);
				mHolder=null;
			}
			
			if(mCameraSV!=null){
				mCameraSV=null;
			}
			Intent intent=new Intent();
			intent.putExtra("data", uri);
			setResult(RESULT_OK, intent);
			finish();
			break;
		}
	}

	// 获取图像回调处理
	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		this.mCameraLay.setVisibility(View.GONE);
		this.mPicLay.setVisibility(View.VISIBLE);
		
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inPreferredConfig = Config.RGB_565;
		opts.inSampleSize =1; 
		Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length,opts);
		Matrix matrixs = new Matrix();
			/*if(orientations > 325 || orientations <= 45){
				Log.v("time", "Surface.ROTATION_0;"+orientations);
				
            }else if(orientations > 45 && orientations <= 135){
            	Log.v("time", " Surface.ROTATION_270"+orientations);
            matrixs.setRotate(180);
            }else if(orientations > 135 && orientations < 225){
            	Log.v("time", "Surface.ROTATION_180;"+orientations);
            matrixs.setRotate(270);
            }else {
            	Log.v("time", "Surface.ROTATION_90"+orientations);
            matrixs.setRotate(0);
            }*/
		matrixs.setRotate(90);
		bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrixs, true);
		
		ContentResolver res = this.getContentResolver();
		ContentValues vals = new ContentValues();
		vals.put(android.provider.MediaStore.Images.Media.TITLE,
				"auto camera title");
		vals.put(android.provider.MediaStore.Images.Media.DISPLAY_NAME,
				"test name");
		uri = res.insert(
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				vals);
		OutputStream outstream = null;
		try {
			outstream = res.openOutputStream(uri);
			bmp.compress(CompressFormat.PNG, 100, outstream);
			outstream.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != outstream) {
				try {
					outstream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				outstream = null;
			}

			// 显示图像
			displayPic(uri);

			// 开始预览，获取图像时系统自动关闭其预览
			// camera.startPreview();
		}
	}

	@Override
	protected void onDestroy() {
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
		
		if(mHolder!=null){
			mHolder.removeCallback(this);
			mHolder=null;
		}
		
		if(mCameraSV!=null){
			mCameraSV=null;
		}
		super.onDestroy();
	}

	// 调整照相机镜头方向
	private void setCameraOrientation() {
		Parameters pm = mCamera.getParameters();

		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// if (Surface.ROTATION_270 ==
			// this.getWindowManager().getDefaultDisplay().getRotation()) {
			if (android.os.Build.VERSION.SDK_INT <= 7) {
				// 2.1及以后
				pm.set("orientation", "landscape");
			} else {
				// 2.2以上
				mCamera.setDisplayOrientation(0);
				pm.setRotation(0);
			}
		} else {
			if (android.os.Build.VERSION.SDK_INT <= 7) {
				// 2.1及以后
				pm.set("orientation", "portrait");
			} else {
				// 2.2以上
				mCamera.setDisplayOrientation(90);
				pm.setRotation(90);
			}
		}
		mCamera.setParameters(pm);
	}

	// 获取相机支持的颜色
	private void getSupportedColorEffects() {
		Parameters pm = mCamera.getParameters();
		// colors.clear();
		// colors.addAll(pm.getSupportedColorEffects());
		// adapter.notifyDataSetChanged();
	}

	// 设置合适的镜头大小
	private void setCameraHeadSize() {
		// WindowManager
		// wm=(WindowManager)this.getSystemService(Context.WINDOW_SERVICE);
		// DisplayMetrics mt=new DisplayMetrics();
		// wm.getDefaultDisplay().getMetrics(mt);
		int vWidth = mCameraSV.getWidth();
		int vHeight = mCameraSV.getHeight();

		int widthRadio = 0;
		int heightRadio = 0;

		Parameters pm = mCamera.getParameters();
		List<Size> sizes = pm.getSupportedPreviewSizes();
		Iterator<Size> itr = sizes.iterator();
		while (itr.hasNext()) {
			Size s = itr.next();
			if (s.width >= widthRadio && s.width <= vWidth
					&& s.height >= heightRadio && s.height <= vHeight) {
				widthRadio = s.width;
				heightRadio = s.height;
			}
		}
		if (widthRadio > 0 && heightRadio > 0) {
			pm.setPreviewSize(widthRadio, heightRadio);
			mCamera.setParameters(pm);
			Toast.makeText(this,
					String.format("size:%1s*%2s", widthRadio, heightRadio),
					Toast.LENGTH_SHORT).show();
		}
	}

	// 显示图像
	private void displayPic(Uri uri) {		
		int width = mCameraSV.getWidth();
		int height = mCameraSV.getHeight();

		int widthRate = 1;
		int heightRate = 1;

		BitmapFactory.Options ops = new BitmapFactory.Options();
		ops.inJustDecodeBounds = true;

		try {
			Bitmap bp = BitmapFactory.decodeStream(this.getContentResolver()
					.openInputStream(uri), null, ops);

			widthRate = (int) Math.ceil(ops.outWidth / (float) width);
			heightRate = (int) Math.ceil(ops.outHeight / (float) height);

			if (widthRate > 1 && heightRate > 1) {
				if (widthRate > heightRate) {
					ops.inSampleSize = widthRate;
				} else {
					ops.inSampleSize = heightRate;
				}
			}
			ops.inJustDecodeBounds = false;
			bp = BitmapFactory.decodeStream(this.getContentResolver()
					.openInputStream(uri), null, ops);
			this.mPicIV.setImageBitmap(bp);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	Timer timer;

	// 自动拍照
	private void autoPhoto() {
		timer = new Timer();

		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mCamera.takePicture(null, null, null,
						CustomCameraActivity.this);
				autoPhoto();
			}
		}, 5000);
	}
	
	
	/**
     * 读取图片属性：旋转的角度
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree  = 0;
        try {
                ExifInterface exifInterface = new ExifInterface(path);                
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                }
        } catch (IOException e) {
                e.printStackTrace();
        }
        return degree;
    }
}